<?php

namespace App\Http\Controllers\Counter;

use App\Cost\CostInterface;
use App\Enums\OrderFrom;
use App\Enums\OrderLogAction;
use App\Enums\OrderType;
use App\Enums\PayChannel;
use App\Enums\AssistantStatus;
use App\Enums\OrderItemType;
use App\Enums\TableStatus;
use App\Enums\TradeStatus;
use App\Enums\UserType;
use App\Helper\ApiResponseHelper;
use App\Http\Controllers\Controller;
use App\Http\Requests\Counter\AssistantItemRequest;
use App\Http\Requests\Counter\GoodsItemRequest;
use App\Http\Requests\Counter\MemberRechargeRequest;
use App\Http\Requests\Counter\OrderBillRequest;
use App\Http\Requests\Counter\OrderChangeTableRequest;
use App\Http\Requests\Counter\OrderCheckRequest;
use App\Http\Requests\Counter\VirtualTableOrderRequest;
use App\Http\Resources\Counter\OnlineTradeOrderResource;
use App\Http\Requests\Counter\TableBillRequest;
use App\Http\Requests\Counter\TableCheckRequest;
use App\Http\Requests\Counter\TableOrderRequest;
use App\Http\Resources\Counter\OrderCollection;
use App\Http\Resources\Counter\OrderResource;
use App\LeShua\LeShua;
use App\Models\CostRule;
use App\Models\Goods;
use App\Models\GoodsStoreStock;
use App\Models\Member;
use App\Models\OnlineTradeOrder;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\OrderLog;
use App\Models\Table;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Spatie\FlareClient\Api;

class OrderController extends Controller
{
    public function create(TableOrderRequest $request)
    {
        $posUser = Auth::user();

        $table = Table::find($request->input('table_id'));
        $costRule = CostRule::find($request->input('cost_rule_id'));

        if (empty($table))
            return ApiResponseHelper::json([], 400, '当前球桌不存在');

        if ($table->status->isOpened())
            return ApiResponseHelper::json([], 400, '当前台球桌使用中');

        if ($table->status == TableStatus::Repair)
            return ApiResponseHelper::json([], 400, '当前台球桌维护中');

        if (empty($costRule))
            return ApiResponseHelper::json([], 400, '收费规则不存在');

        if (!empty($request->member_id) && empty(Member::find($request->member_id)))
            return ApiResponseHelper::json([], 400, '会员不存在');

        $order = Order::createTableOrder($posUser, $table, $costRule);
        $order->member_id = $request->member_id;
        $order->save();
        $this->orderLoad($order);

        return new OrderResource($order);
    }

    public function createVirtualTableOrder(VirtualTableOrderRequest $request)
    {
        $posUser = Auth::user();

        $table = Table::find($request->input('table_id'));

        if (empty($table))
            return ApiResponseHelper::json([], 400, '当前球桌不存在');

        if ($table->status->isOpened())
            return ApiResponseHelper::json([], 400, '当前台球桌使用中');

        if ($table->status == TableStatus::Repair)
            return ApiResponseHelper::json([], 400, '当前台球桌维护中');

        if (!empty($request->member_id))
            $member = Member::find($request->member_id);

        $order = Order::createVirtualTableOrder($posUser, $table, $member ?? null);

        $this->orderLoad($order);

        return new OrderResource($order);
    }

    public function getTableOrder(Table $table)
    {
        $order = $table->tableOrder;
        $this->orderLoad($order);

        return new OrderResource($order);
    }

    public function setOrderItemFree(Order $order, OrderItem $item)
    {
        if ($order->status != TradeStatus::Created)
            return ApiResponseHelper::json([], 400, '当前订单状态无法设置商品为赠品');

        try {
            DB::transaction(function () use ($order, $item) {

                $item->is_free = true;
                $item->money = 0;
                $item->origin_money = 0;
                $item->save();

                $order->sumMoney();
                $order->save();
            });
        } catch (\Exception $exception) {
            return ApiResponseHelper::json([], 400, $exception->getMessage());
        }

        $order->refresh();
        $this->orderLoad($order);
        return new OrderResource($order);
    }

    public function addGoodsItem(GoodsItemRequest $request)
    {
        if (!empty($request->table_id)) {

            $table = Table::find($request->table_id);

            if (empty($table))
                return ApiResponseHelper::json([], 400, '当前球桌不存在');

            if (!$table->status->isOpened())
                return ApiResponseHelper::json([], 400, '当前台球桌未开台');

            $order = $table->tableOrder;
        }

        if (!empty($request->order_id)) {

            $order = Order::find($request->order_id);

            if (empty($order))
                return ApiResponseHelper::json([], 400, '当前订单不存在');

            if ($order->status != TradeStatus::Created)
                return ApiResponseHelper::json([], 400, '当前订单已支付，无法添加商品');
        }

        //新的纯商品订单
        if (!isset($order)) {
            $order = Order::createEmptyOrder(Auth::user());
        }

        $goods = Goods::with([
            'stocks' => function($query) {
                $query->where('store_id', Auth::user()->store_id);
            }
        ])->find($request->input('goods_id'));

        if (empty($goods))
            return ApiResponseHelper::json([], 400, '商品不存在');

        $count = $request->input('count');
        $specification = $request->input('specification');

        if ($goods->stocks->isEmpty() || ($goods->stocks->first()->stock_num <= 0 && $count > 0))
            return ApiResponseHelper::json([], 400, '商品已售罄');

        if (!empty($request->order_item_id)) {

            $orderItem = OrderItem::find($request->order_item_id);
        } else {

            $orderItem = $order->items()->where('goods_id', $goods->id);
            if (!empty($specification))
                $orderItem = $orderItem->where('specification', $specification);
            $orderItem = $orderItem->first();
            if ($count == 0) {
                return ApiResponseHelper::json([], 400, '商品数量不可为0');
            } else if ($count < 0) {

                if (empty($orderItem) || $orderItem->count < abs($count))
                    return ApiResponseHelper::json([], 400, '商品退还数量错误，请勿大于购买数量');
            }
        }

        try {
            DB::transaction(function () use ($order,$goods, $orderItem, $count, $specification) {

                if (empty($orderItem)) {
                    $orderItem = $order->items()->create([
                        'goods_id' => $goods->id,
                        'count' => $count,
                        'money' => $goods->price * $count,
                        'origin_money' => $goods->price * $count,
                        'specification' => $specification,
                    ]);
                    OrderLog::create([
                        'order_id' => $order->id,
                        'order_item_id' => $orderItem->id,
                        'user_id' => Auth::id(),
                        'action' => OrderLogAction::AddGoods,
                        'per_quantity' => 0,
                        'after_quantity' => $count,
                    ]);
                } else {

                    OrderLog::create([
                        'order_id' => $order->id,
                        'order_item_id' => $orderItem->id,
                        'user_id' => Auth::id(),
                        'action' => OrderLogAction::ChangeGoodsQuantity,
                        'per_quantity' => $orderItem->count,
                        'after_quantity' => $orderItem->count + $count,
                    ]);

                    if ($count < 0 && $orderItem->count == abs($count)) {
                        $orderItem->delete();
                    } else {
                        $orderItem->count += $count;

                        if ($orderItem->is_free) {
                            $orderItem->money = 0;
                            $orderItem->origin_money = 0;
                        } else {
                            $orderItem->money = $goods->price * $orderItem->count;
                            $orderItem->origin_money = $goods->price * $orderItem->count;
                        }
                        $orderItem->save();
                    }
                }

                //先扣减库存，虽然不知道该不该现在减
                GoodsStoreStock::addStock(Auth::user()->store_id, $goods->id, -$count);

                //订单表金额增减
                $order->sumMoney();
                $order->save();
            });
        } catch (\Exception $exception) {
//            throw $exception;
            return ApiResponseHelper::json([], 400, $exception->getMessage());
        }

        $this->orderLoad($order);

        return new OrderResource($order);
    }

    public function addAssistantItem(AssistantItemRequest $request)
    {
        $posUser = Auth::user();
        $table = Table::find($request->input('table_id'));
        $costRule = CostRule::find($request->input('cost_rule_id'));
        $assistantUser = User::withType(UserType::Assistant)
            ->withStore($posUser->store_id)
            ->find($request->input('user_id'));

        if (empty($table))
            return ApiResponseHelper::json([], 400, '当前球桌不存在');

        if (!$table->status->isOpened())
            return ApiResponseHelper::json([], 400, '当前台球桌未开台');

        if ($assistantUser->assistant_status != AssistantStatus::NotOnDuty)
            return ApiResponseHelper::json([], 400, '当前助教正忙');

        $order = $table->tableOrder;

        DB::transaction(function () use ($posUser, $order, $costRule, $assistantUser, $table) {

            $orderItem = $order->items()->create([
                'count' => 1,
                'money' => 0,
                'origin_money' => 0,
                'type' => \App\Enums\OrderItemType::Assistant,
                'cost_rule_id' => $costRule->id,
                'assistant_user_id' => $assistantUser->id,
                'start_at' => now(),
                'is_virtual' => $table->status->isVirtual(),
            ]);

            $assistantUser->assistant_status = AssistantStatus::OnDuty;
            $assistantUser->save();
        });

        $this->orderLoad($order);
        return new OrderResource($order);
    }

    public function removeAssistantItem(OrderItem $item)
    {
        if ($item->type != \App\Enums\OrderItemType::Assistant)
            return ApiResponseHelper::json([], 400, '当前订单项不是助教');

        if (!$item->order->status->canPay())
            return ApiResponseHelper::json([], 400, '当前订单已支付，无法删除');

        DB::transaction(function () use ($item) {

            $item->delete();

            $order = $item->order;
            $order->sumMoney();
            $order->save();

            $assistantUser = $item->assistantUser;
            $assistantUser->assistant_status = AssistantStatus::NotOnDuty;
            $assistantUser->save();
        });

        $this->orderLoad($item->order);
        return new OrderResource($item->order);
    }

    public function checkAssistantItem(OrderItem $item)
    {
        if ($item->type != \App\Enums\OrderItemType::Assistant)
            return ApiResponseHelper::json([], 400, '当前订单项不是助教');

        DB::transaction(function () use ($item) {

            $endAt = date('Y-m-d H:i:s');
            $this->finishAssistantItem($item, $endAt);

            //TODO: 上钟日志等
        });

        $this->orderLoad($item->order);
        return new OrderResource($item->order);
    }

    public function getOrderBill(Order $order, OrderBillRequest $request)
    {
        $finishDate = $request->input('finish_date');

        try {
            //string to boolean
            $noYuan = $request->input('no_yuan') == 'true';
            $noJiao = $request->input('no_jiao') == 'true';
            $noFen = $request->input('no_fen') == 'true';

            $details = [
                'table_orders' => [],
                'total_money' => 0
            ];
            $total = 0;
            $tableItem = $order->getTableItem();

            //是台桌订单
            if (!empty($tableItem)) {

                /**
                 * @var Table $table
                 */
                $table = $tableItem->table;
                if (!$table->status->isVirtual()) {

                    $costRule = $tableItem->costRule->data;
                    $tablePrice = $costRule->getPrice($tableItem->start_at, $finishDate);
                    $tableTotalMoney = ($tablePrice->basePrice + $tablePrice->timeOutPrice) / 100;

                    $orderDetail = [
                        'table' => $table,
                        'order' => $table->tableOrder,
                        'table_money' => [
                            'base_money' => $tablePrice->basePrice / 100,
                            'timeout_minute' => $tablePrice->timeOutMinute / 100,
                            'timeout_money' => $tablePrice->timeOutPrice / 100,
                            'message' => $tablePrice->message,
                            'total_money' => $tableTotalMoney
                        ],
                        'total_money' => $order->money + $tableTotalMoney
                    ];

                    $details['table_orders'] = $orderDetail;
                    $total += $orderDetail['total_money'];
                }
            } else {

                $total = $order->money;
            }

            $details['no_yuan'] = 0;
            $details['no_jiao'] = 0;
            $details['no_fen'] = 0;

            if ($noYuan) {
                $newTotal = $this->noYuan($total);
                $details['no_yuan'] = $newTotal - $total;
                $total = $newTotal;
            }

            if ($noJiao) {
                $newTotal = $this->noJiao($total);
                $details['no_jiao'] = $newTotal - $total;
                $total = $newTotal;
            }

            if ($noFen) {
                $newTotal = $this->noFen($total);
                $details['no_fen'] = $newTotal - $total;
                $total = $newTotal;
            }

            $details['total_money'] = $total;
            $details['discount_money'] = $details['no_yuan'] + $details['no_jiao'] + $details['no_fen'];

            return ApiResponseHelper::json($details);

        } catch (\Exception $exception) {
            return ApiResponseHelper::json([], 400, $exception->getMessage());
        }
    }

    public function orderCheck(Order $order, OrderCheckRequest $request)
    {
        $type = PayChannel::from($request->type);
        /**
         * @var Member $card
         */
        $card = null;
        if ($type == PayChannel::Member) {

            /**
             * @var Member $card
             */
            $card = Member::withPhone($request->bar_code)->first();
            if (empty($card))
                return ApiResponseHelper::json([], 400, '会员卡不存在');

            if (!$card->checkPassword($request->password))
                return ApiResponseHelper::json([], 400, '会员卡密码错误');
        }

        foreach ($order->items as $item) {
            //判断是否有未结算的助教
            if ($item->type == OrderItemType::Assistant && $item->end_at == null)
                return ApiResponseHelper::json([], 400, '当前订单有未结算的助教');
        }

        if (!$order->status->canPay())
            return ApiResponseHelper::json([], 400, '当前订单已支付，无法结算');

        try {

            DB::transaction(function () use ($card, $type, $request, $order, &$tradeOrder) {

                $tableItem = $order->getTableItem();
                $finishDate = $request->finish_date;

                //是台桌订单
                if (!empty($tableItem) && !in_array($order->status, [TradeStatus::Pending, TradeStatus::PendingOpen])) {
                    $this->finishTableItem($tableItem, $finishDate);
                }

                //更新订单
                $order->pay_channel = $type;
                $order->sumMoney();
                if ($type == PayChannel::Member) {
                    $order->member_id = $card->id;
                    //会员卡支付
                    $card->consume($order->money, Auth::user(), '订单消费', $order);
                }
                $order->save();

                $totalMoney = $order->money;

                //进行抹零操作
                $noYuan = $request->input('no_yuan') == 'true';
                $noJiao = $request->input('no_jiao') == 'true';
                $noFen = $request->input('no_fen') == 'true';

                $discountMoney = 0;
                if ($noYuan) {
                    $newTotalMoney = $this->noYuan($totalMoney);
                    $discountMoney += $newTotalMoney - $totalMoney;
                    $totalMoney = $newTotalMoney;
                }

                if ($noJiao) {
                    $newTotalMoney = $this->noJiao($totalMoney);
                    $discountMoney += $newTotalMoney - $totalMoney;
                    $totalMoney = $newTotalMoney;
                }

                if ($noFen) {
                    $newTotalMoney = $this->noFen($totalMoney);
                    $discountMoney += $newTotalMoney - $totalMoney;
                    $totalMoney = $newTotalMoney;
                }

                if ($discountMoney != 0) {
                    $order->discount_money = $discountMoney;
                    $order->money = $totalMoney;
                    $order->save();
                }

                if ($type == PayChannel::LeShua) {

                    /**
                     * @var OnlineTradeOrder $tradeOrder
                     */
                    $tradeOrder = OnlineTradeOrder::create([
                        'order_no' => OnlineTradeOrder::genOrderNo(),
                        'order_ids' => [$order->id],
                        'total_money' => $totalMoney,
                        'status' => TradeStatus::Created,
                        'store_id' => Auth::user()->store_id,
                    ]);
                    $store = $order->store;
                    $payment = new LeShua($store->leshua_num);
                    $response = $payment->scanPay($request->bar_code, $tradeOrder->order_no, $totalMoney * 100);

                    if ($response->getStatus() == 2)
                        $tradeOrder->payed();
                    else
                        $tradeOrder->wait();
                }

                if (in_array($type, [
                    PayChannel::Member,
                    PayChannel::Cash,
                    PayChannel::Bad,
                    PayChannel::MeiTuan,
                    PayChannel::DouYin,
                ])) {
                    Order::orderIdsPayed([$order->id], $type);
                }
            });

            if ($type == PayChannel::LeShua)
                return new OnlineTradeOrderResource($tradeOrder);

            return ApiResponseHelper::json([]);

        } catch (\Exception $exception) {
            return ApiResponseHelper::json([], 400, $exception->getMessage());
        }
    }

    public function onlineTradeConfirm(OnlineTradeOrder $tradeOrder)
    {
        if ($tradeOrder->status == TradeStatus::Payed)
            return ApiResponseHelper::json(['status' => $tradeOrder->status]);

        $store = $tradeOrder->store;
        $payment = new LeShua($store->leshua_num);
        $response = $payment->getOrderInfo($tradeOrder->order_no);

        if ($response->getStatus() == 2) {
            $tradeOrder->payed();
        }

        if ($response->getStatus() == 6) {
            $tradeOrder->cancel();
        }

        return ApiResponseHelper::json(['status' => $tradeOrder->status]);
    }

    public function memberRecharge(Member $member, MemberRechargeRequest $request)
    {
        try {
            $payChannel = PayChannel::from($request->type);

            DB::transaction(function () use ($member, $request, $payChannel, &$tradeOrder) {
                //先创建充值订单
                /**
                 * @var Order $order
                 */
                $order = Order::create([
                    'order_no' => Order::generateOrderNo(),
                    'user_id' => Auth::id(),
                    'member_id' => $member->id,
                    'store_id' => Auth::user()->store_id,
                    'status' => TradeStatus::Created,
                    'money' => $request->balance,
                    'pay_channel' => $payChannel,
                    'comment' => '会员储值',
                    'type' => OrderType::MemberRecharge,
                    'from' => OrderFrom::Counter,
                    'give_money' => $request->balance_give,
                    'origin_money' => $request->balance,
                    'member_balance_type' => $request->balance_type,
                ]);

                if ($payChannel == PayChannel::LeShua) {

                    /**
                     * @var OnlineTradeOrder $tradeOrder
                     */
                    $tradeOrder = OnlineTradeOrder::create([
                        'order_no' => OnlineTradeOrder::genOrderNo(),
                        'order_ids' => [$order->id],
                        'total_money' => $order->money,
                        'status' => TradeStatus::Created,
                        'store_id' => Auth::user()->store_id,
                    ]);

                    $store = Auth::user()->store;
                    $payment = new LeShua($store->leshua_num);
                    $response = $payment->scanPay($request->bar_code, $tradeOrder->order_no, $order->money * 100);

//                    Log::info($response->getAll());
//                    Log::info($response->getStatus());
//                    Log::info(\typeOf($response->getStatus()));

                    if ($response->getStatus() == 2)
                        $tradeOrder->payed();
                    else
                        $tradeOrder->wait();

//                    if ($response->getStatus() == 1)
//                        $tradeOrder->wait();
                } else {
                    $order->orderPayed($payChannel);
                }
            });

            if ($payChannel == PayChannel::LeShua)
                return new OnlineTradeOrderResource($tradeOrder);

            return ApiResponseHelper::json([]);

        } catch (\Exception $exception) {
            return ApiResponseHelper::json([], 400, $exception->getMessage());
        }
    }

    public function changeTable(OrderChangeTableRequest $request)
    {
        $table = Table::find($request->table_id);
        $toTable = Table::find($request->to_table_id);

        if (empty($table) || empty($toTable))
            return ApiResponseHelper::json([], 400, '球桌不存在');

        if (!$table->status->isOpened())
            return ApiResponseHelper::json([], 400, '当前球桌未开台');

        if ($toTable->status->isOpened())
            return ApiResponseHelper::json([], 400, '目标球桌已开台');

        DB::transaction(function () use ($table, $toTable, &$order) {

            /**
             * @var Order $order
             * @var OrderItem $tableItem
             */
            $order = $table->tableOrder;

            $tableItem = $order->getTableItem();
            $tableItem->table_id = $toTable->id;
            $tableItem->save();

            //更新目标台桌
            $toTable->status = $table->status;
            $toTable->table_order_id = $table->table_order_id;
            $toTable->save();

            //更新台桌
            $table->status = TableStatus::Idle;
            $table->table_order_id = null;
            $table->save();
        });

        $this->orderLoad($order);
        return new OrderResource($order);
    }

    public function getOrder(Order $order)
    {
        $this->orderLoad($order);

        return new OrderResource($order);
    }

    public function setOrderComment(Order $order, Request $request)
    {
        $order->comment = $request->comment;
        $order->save();

        $this->orderLoad($order);

        return new OrderResource($order);
    }

    public function getOrderList(Request $request)
    {
        $query = Order::latest()->where('type', OrderType::Counter)->with([
            'items', 'items.goods', 'items.table.tableType', 'items.costRule', 'items.assistantUser',
            'user', 'member', 'store',
        ]);

        if (!empty($request->store_id))
            $query = $query->where('store_id', $request->store_id);

        if (!empty($request->table_id)) {
            $query = $query->whereHas('items', function ($query) use ($request) {
                $query->where('table_id', $request->table_id);
            });
        }

        if (!empty($request->status))
            $query = $query->where('status', $request->status);
        else
            $query = $query->whereNotIn('status', [TradeStatus::Pending, TradeStatus::PendingOpen]);

        return new OrderCollection($query->paginate());
    }

    public function pending(Order $order)
    {
        try {
            $this->pendingOrder($order, TradeStatus::Pending);
        } catch (\Exception $exception) {
            return ApiResponseHelper::json([], 400, $exception->getMessage());
        }

        return ApiResponseHelper::json([]);
    }

    public function pendingOpen(Order $order)
    {
        try {
            $this->pendingOrder($order, TradeStatus::PendingOpen);
        } catch (\Exception $exception) {
            return ApiResponseHelper::json([], 400, $exception->getMessage());
        }

        return ApiResponseHelper::json([]);
    }

    public function pauseOrderItem(Order $order, OrderItem $item)
    {
        $item->pause();
        $this->orderLoad($order);

        return new OrderResource($order);
    }

    public function unpauseOrderItem(Order $order, OrderItem $item)
    {
        $item->unpause();
        $this->orderLoad($order);

        return new OrderResource($order);
    }

    private function pendingOrder(Order $order, TradeStatus $status)
    {
        if ($order->status != TradeStatus::Created)
            throw new \Exception('当前订单已支付或已取消，无法挂单');

        if (!in_array($status, [TradeStatus::Pending, TradeStatus::PendingOpen]))
            throw new \Exception('挂单状态错误');

        DB::transaction(function () use ($order, $status) {

            if ($status == TradeStatus::Pending) {
                OrderLog::create([
                    'order_id' => $order->id,
                    'user_id' => Auth::id(),
                    'action' => OrderLogAction::PendingOrder,
                ]);
            }

            $order->status = $status;
            $order->save();

            $items = $order->items;
            foreach ($items as $item) {
                if ($item->type == OrderItemType::Table)
                    $this->finishTableItem($item, now());

                if ($item->type == OrderItemType::Assistant)
                    $this->finishAssistantItem($item, now());
            }

            $order->sumMoney();

        });
    }

    private function finishAssistantItem(OrderItem $item, $endAt)
    {
        //解除暂停
        $item->unpause();

        $money = $item->getTotalMoney($endAt);

        $item->end_at = $endAt;
        $item->money = $money;
        $item->origin_money = $money;
        $item->save();

        $order = $item->order;
        $order->sumMoney();
        $order->save();

        $assistantUser = $item->assistantUser;
        $assistantUser->assistant_status = AssistantStatus::NotOnDuty;
        $assistantUser->save();
    }

    private function finishTableItem(OrderItem $tableItem, $finishDate)
    {
        /**
         * @var Table $table
         */
        $table = $tableItem->table;

        if ($table->status->isVirtual())
            $tableTotalMoney = $tableItem->getTotalMoney($finishDate);
        else
            $tableTotalMoney = 0;

        //更新台桌item
        $tableItem->end_at = $finishDate;
        $tableItem->money = $tableTotalMoney;
        $tableItem->origin_money = $tableTotalMoney;
        $tableItem->save();

        //更新台桌
        $table->status = TableStatus::Idle;
        $table->table_order_id = null;
        $table->use_start_at = null;
        $table->save();

        $order = $tableItem->order;
        $order->sumMoney();
        $order->save();
    }

    private function orderLoad(Order $order)
    {
        $order->load([
            'items', 'items.goods', 'items.table.tableType', 'items.costRule', 'items.assistantUser',
            'user', 'member', 'store',
        ]);
    }

    private function noYuan($total)
    {
        $integerPart = floor($total); // 获取整数部分
        $decimalPart = $total - $integerPart; // 获取小数部分
        return floor($integerPart / 10) * 10 + $decimalPart;
    }

    private function noJiao($total)
    {
        // 获取整数部分
        $integerPart = floor($total);

        // 获取小数部分
        $decimalPart = $total - $integerPart;

        if ($decimalPart == 0) {
            // 如果没有小数部分，直接返回原来的数字
            return $total;
        }

        // 将小数部分转换为字符串，并将第一位设为0
        $decimalStr = (string)$decimalPart;
        $decimalStr[2] = '0'; // 小数点后的第一位为字符串的第三位

        // 将字符串转换回浮点数
        $newDecimalPart = (float)$decimalStr;

        // 组合整数部分和新的小数部分
        $newTotal = $integerPart + $newDecimalPart;

        return $newTotal;
    }

    private function noFen($total)
    {
        // 获取整数部分
        $integerPart = floor($total);

        // 获取小数部分
        $decimalPart = $total - $integerPart;

        if ($decimalPart == 0) {
            // 如果没有小数部分，直接返回原来的数字
            return $total;
        }

        // 将小数部分放大100倍，便于操作第二位
        $decimalPart = $decimalPart * 100;

        // 获取放大后的整数部分
        $decimalIntPart = floor($decimalPart);

        // 将第二位设为0
        $decimalIntPart = floor($decimalIntPart / 10) * 10;

        // 还原小数部分
        $newDecimalPart = $decimalIntPart / 100;

        // 组合整数部分和新的小数部分
        $newTotal = $integerPart + $newDecimalPart;

        return $newTotal;
    }
}
